package cn.tworice.auth.service.impl;

import cn.tworice.auth.service.SQLInjectionService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

@Service
public class DefaultSQLInjectionServiceImpl implements SQLInjectionService {

    /**
     * 定义一些常见的SQL注入模式
     */
    private static final Pattern SQL_INJECTION_PATTERN = Pattern.compile(
            "(?i)(\\b(select|update|delete|insert|truncate|alter|drop|create|exec|execute|declare|union|merge|call|or)\\b|--|;|'|\"|/\\*|\\*/|\\bx\\')"
    );

    @Override
    public boolean isSQLInjection(HttpServletRequest request) {
        // 获取请求路径
        String requestPath = request.getRequestURI();

        // 检查请求路径是否包含SQL注入
        if (SQL_INJECTION_PATTERN.matcher(requestPath).find()) {
            return true;
        }

        // 获取请求参数并检查是否包含SQL注入
        for (String[] paramValues : request.getParameterMap().values()) {
            for (String paramValue : paramValues) {
                if (paramValue != null && SQL_INJECTION_PATTERN.matcher(paramValue).find()) {
                    return true;
                }
            }
        }

        // 如果没有发现SQL注入，返回false
        return false;
    }
}
